﻿using SF.Common;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace SF.Ucenter.admin.good
{
    public partial class good_type_edit : SF.Web.UI.ManagePage
    {
        private string action = DTEnums.ActionEnum.Add.ToString(); //操作类型
        private int id = 0;

        protected void Page_Load(object sender, EventArgs e)
        {
            string _action = DTRequest.GetQueryString("action");
            this.id = DTRequest.GetQueryInt("id");

            if (!string.IsNullOrEmpty(_action))
            {
                if (_action == DTEnums.ActionEnum.Edit.ToString())
                {
                    this.action = DTEnums.ActionEnum.Edit.ToString();//修改类型
                    if (this.id == 0)
                    {
                        JscriptMsg("传输参数不正确！", "back");
                        return;
                    }
                    if (!new BLL.bs_good_type().Exists(this.id))
                    {
                        JscriptMsg("类别不存在或已被删除！", "back");
                        return;
                    }
                }

            }
            if (!Page.IsPostBack)
            {
                ChkAdminLevel("good_type_list", DTEnums.ActionEnum.View.ToString()); //检查权限
                //绑定 商品类型
                BLL.sf_goods_alltype bll = new BLL.sf_goods_alltype();
                string templatesNum = Session[DTKeys.SESSION_TEMPLATES_INFO].ToString();
                string where = new BLL.sf_modeconfig().GetModel("settingNum='" + templatesNum + "'").goodstype_onshelf;
                DataTable dt = bll.GetList("typeNum='" + where + "'").Tables[0];
                this.ddlGoodsTypeId.Items.Clear();
                this.ddlGoodsTypeId.Items.Add(new ListItem("请选择类型...", ""));
                foreach (DataRow dr in dt.Rows)
                {
                    this.ddlGoodsTypeId.Items.Add(new ListItem(dr["typeName"].ToString().Trim(), dr["typeNum"].ToString()));
                }
                if (this.ddlGoodsTypeId.Items.Count > 1)
                {
                    this.ddlGoodsTypeId.SelectedValue = this.ddlGoodsTypeId.Items[1].Value;  //默认为通用
                    TreeBind(this.ddlGoodsTypeId.SelectedValue);
                }
                if (action == DTEnums.ActionEnum.Edit.ToString()) //修改
                {
                    ShowInfo(this.id);
                    ShowFieldList(this.id);
                }
                else
                {
                    if (this.id > 0)
                    {
                        this.ddlParentId.SelectedValue = this.id.ToString();
                    }
                    txtTitle.Attributes.Add("ajaxurl", "../../tools/goods_ajax.ashx?action=goods_type_name_validate");
                }
            }
        }

        /// <summary>
        /// 显示字段列表
        /// </summary>
        /// <param name="_id"></param>
        private void ShowFieldList(int _id)
        {
            BLL.bs_good_type_field bll = new BLL.bs_good_type_field();
            string _strWhere = string.Format(" goodTypeId='{0}'", _id);
            var list = bll.GetModelList(_strWhere);
            this.rptList.DataSource = list;
            this.rptList.DataBind();
        }

        #region 绑定类别
        private void TreeBind(string typeid)
        {
            Model.manager mgr = Session[DTKeys.SESSION_ADMIN_INFO] as Model.manager;
            string busnieseNum = mgr.busnieseNum.ToString();
            string appNum = Session[DTKeys.SESSION_APP_INFO].ToString();
            string templatesNum = Session[DTKeys.SESSION_TEMPLATES_INFO].ToString();

            BLL.bs_good_type bll = new BLL.bs_good_type();
            DataTable dt = bll.GetList(0, "goodAllTypeNum='" + typeid + "' and " + Utils.getWhereByInfo(busnieseNum, appNum, templatesNum), "id asc").Tables[0];

            this.ddlParentId.Items.Clear();
            this.ddlParentId.Items.Add(new ListItem("无父级分类", "0"));
            foreach (DataRow dr in dt.Rows)
            {
                string Id = dr["id"].ToString();
                int ClassLayer = int.Parse(dr["class_layer"].ToString());
                string Title = dr["typeName"].ToString().Trim();

                if (ClassLayer == 1)
                {
                    this.ddlParentId.Items.Add(new ListItem(Title, Id));
                }
                else
                {
                    Title = "├ " + Title;
                    Title = Utils.StringOfChar(ClassLayer - 1, "　") + Title;
                    this.ddlParentId.Items.Add(new ListItem(Title, Id));
                }
            }
        }
        #endregion

        #region 赋值操作
        private void ShowInfo(int _id)
        {
            BLL.bs_good_type bll = new BLL.bs_good_type();
            Model.bs_good_type model = bll.GetModel(_id);
            if (model.isShow == 1)
            {
                cbIsLock.Checked = true;
            }
            else
            {
                cbIsLock.Checked = false;
            }

            ddlGoodsTypeId.SelectedValue = model.goodAllTypeNum;
            TreeBind(model.goodAllTypeNum.ToString());
            ddlParentId.SelectedValue = model.fatherId.ToString();
            txtTitle.Text = model.typeName;
            txtSortId.Text = model.sort.ToString();

            txtImgUrl.Text = model.pics;
            imgHeadPic.ImageUrl = model.pics;
        }
        #endregion

        #region 增加操作
        private bool DoAdd()
        {
            try
            {
                Model.manager mgr = Session[DTKeys.SESSION_ADMIN_INFO] as Model.manager;
                string busnieseNum = mgr.busnieseNum.ToString();
                string appNum = Session[DTKeys.SESSION_APP_INFO].ToString();
                string templatesNum = Session[DTKeys.SESSION_TEMPLATES_INFO].ToString();

                Model.bs_good_type model = new Model.bs_good_type();
                BLL.bs_good_type bll = new BLL.bs_good_type();
                model.typeName = txtTitle.Text.Trim();
                model.fatherId = int.Parse(ddlParentId.SelectedValue);
                model.sort = int.Parse(txtSortId.Text.Trim());
                model.pics = Request.Form["txtImgUrl"].Trim();
                model.goodAllTypeNum = ddlGoodsTypeId.SelectedValue;
                model.busnieseNum = busnieseNum;
                model.appNum = appNum;
                model.templatesNum = templatesNum;
                if (cbIsLock.Checked == true)
                {
                    model.isShow = 1;
                }
                else
                {
                    model.isShow = 0;
                }
                var goodTypeId = bll.Add(model);
                if (goodTypeId > 0)
                {
                    AddAdminLog(DTEnums.ActionEnum.Add.ToString(), "添加商品分类:" + model.typeName); //记录日志
                    SaveFields(goodTypeId, false);  //保存字段
                    return true;
                }
            }
            catch
            {
                return false;
            }
            return false;
        }
        #endregion

        #region 修改操作
        private bool DoEdit(int _id)
        {
            try
            {
                BLL.bs_good_type bll = new BLL.bs_good_type();
                Model.bs_good_type model = bll.GetModel(_id);

                int FatherID = int.Parse(ddlParentId.SelectedValue);
                //如果选择的父ID不是自己,则更改
                if (FatherID != model.id)
                {
                    model.fatherId = FatherID;
                }

                model.typeName = txtTitle.Text.Trim();
                model.sort = int.Parse(txtSortId.Text.Trim());
                model.pics = Request.Form["txtImgUrl"].Trim();
                model.goodAllTypeNum = ddlGoodsTypeId.SelectedValue;
                if (cbIsLock.Checked == true)
                {
                    model.isShow = 1;
                }
                else
                {
                    model.isShow = 0;
                }
                if (bll.Update(model))
                {
                    AddAdminLog(DTEnums.ActionEnum.Edit.ToString(), "修改商品分类:" + model.typeName); //记录日志
                    SaveFields(_id, true);  //保存字段定义
                    return true;
                }
            }
            catch
            {
                return false;
            }
            return false;
        }
        #endregion

        /// <summary>
        /// 保存字段定义
        /// </summary>
        /// <param name="goodTypeId"></param>
        /// <param name="isUpdate"></param>
        /// <returns></returns>
        private bool SaveFields(long goodTypeId, bool isUpdate)
        {
            BLL.bs_good_type_field bll = new BLL.bs_good_type_field();

            //如果是更新，则先清除原有记录
            if (isUpdate)
            {
                bll.DeleteByGoodTypeId(goodTypeId);
            }

            Model.manager mgr = Session[DTKeys.SESSION_ADMIN_INFO] as Model.manager;
            string busnieseNum = mgr.busnieseNum.ToString();
            string appNum = Session[DTKeys.SESSION_APP_INFO].ToString();
            string templatesNum = Session[DTKeys.SESSION_TEMPLATES_INFO].ToString();
            Model.bs_good_type_field field;
            //取得列表的数据，每行添加到数据库中
            foreach (RepeaterItem item in rptList.Items)
            {
                field = new Model.bs_good_type_field();
                //int fieldId = Convert.ToInt32(((HiddenField)item.FindControl("hidId")).Value);
                //field.id = fieldId;
                field.busnieseNum = busnieseNum;
                field.appNum = appNum;
                field.templatesNum = templatesNum;
                field.fieldCode = ((TextBox)item.FindControl("txtFieldCode")).Text;
                field.fieldName = ((TextBox)item.FindControl("txtFildName")).Text;
                field.fieldType = ((TextBox)item.FindControl("txtFieldType")).Text;
                var fieldLengthText = ((TextBox)item.FindControl("txtFieldLength")).Text;
                if (!String.IsNullOrWhiteSpace(fieldLengthText))
                    field.fieldLength = Convert.ToInt32(fieldLengthText);
                var fieldPrecisionText = ((TextBox)item.FindControl("txtFieldPrecision")).Text;
                if (!String.IsNullOrWhiteSpace(fieldPrecisionText))
                    field.fieldPrecision = Convert.ToInt32(fieldPrecisionText);
                field.fieldRemark = ((TextBox)item.FindControl("txtFieldRemark")).Text;
                field.goodTypeId = this.id;

                if (bll.Add(field) == 0)
                    return false;
            }
            return true;
        }

        //保存类别
        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            if (action == DTEnums.ActionEnum.Edit.ToString()) //修改
            {
                ChkAdminLevel("good_type_list", DTEnums.ActionEnum.Edit.ToString()); //检查权限
                if (!DoEdit(this.id))
                {
                    JscriptMsg("保存过程中发生错误！", "", "Error");
                    return;
                }
                JscriptMsg("修改类别成功！", "good_type_list.aspx");
            }
            else //添加
            {
                ChkAdminLevel("good_type_list", DTEnums.ActionEnum.Add.ToString()); //检查权限
                if (!DoAdd())
                {
                    JscriptMsg("保存过程中发生错误！", "", "Error");
                    return;
                }
                JscriptMsg("添加类别成功！", "good_type_list.aspx");
            }
        }

        protected void ddlGoodsTypeId_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(ddlGoodsTypeId.SelectedValue.ToString()))
            {
                TreeBind(ddlGoodsTypeId.SelectedValue.ToString());
            }
        }

        #region 字段列表编辑
        /// <summary>
        /// 新增字段
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnAddField_Click(object sender, EventArgs e)
        {
            BLL.bs_good_type_field bll = new BLL.bs_good_type_field();
            var list = bll.GetModelList("1=0");

            Model.manager mgr = Session[DTKeys.SESSION_ADMIN_INFO] as Model.manager;
            string busnieseNum = mgr.busnieseNum.ToString();
            string appNum = Session[DTKeys.SESSION_APP_INFO].ToString();
            string templatesNum = Session[DTKeys.SESSION_TEMPLATES_INFO].ToString();

            Model.bs_good_type_field field;

            foreach (RepeaterItem item in rptList.Items)
            {
                field = new Model.bs_good_type_field();
                int fieldId = Convert.ToInt32(((HiddenField)item.FindControl("hidId")).Value);
                field.id = fieldId;
                field.busnieseNum = busnieseNum;
                field.appNum = appNum;
                field.templatesNum = templatesNum;
                field.fieldCode = ((TextBox)item.FindControl("txtFieldCode")).Text;
                field.fieldName = ((TextBox)item.FindControl("txtFildName")).Text;
                field.fieldType = ((TextBox)item.FindControl("txtFieldType")).Text;
                var fieldLengthText = ((TextBox)item.FindControl("txtFieldLength")).Text;
                if (!String.IsNullOrWhiteSpace(fieldLengthText))
                    field.fieldLength = Convert.ToInt32(fieldLengthText);
                var fieldPrecisionText = ((TextBox)item.FindControl("txtFieldPrecision")).Text;
                if (!String.IsNullOrWhiteSpace(fieldPrecisionText))
                    field.fieldPrecision = Convert.ToInt32(fieldPrecisionText);
                field.fieldRemark = ((TextBox)item.FindControl("txtFieldRemark")).Text;
                field.goodTypeId = this.id;
                list.Add(field);
            }
            //新增一行
            field = new Model.bs_good_type_field();
            //id用随机数来替代
            Random ran = new Random();
            field.id = ran.Next(1000, 9999);
            field.busnieseNum = busnieseNum;
            field.appNum = appNum;
            field.templatesNum = templatesNum;
            field.fieldType = "string";
            field.fieldLength = 255;
            field.goodTypeId = this.id;
            list.Add(field);

            this.rptList.DataSource = list;
            this.rptList.DataBind();
        }

        /// <summary>
        /// 删除字段
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnDeleteField_Click(object sender, EventArgs e)
        {
            BLL.bs_good_type_field bll = new BLL.bs_good_type_field();
            var list = bll.GetModelList("1=0");

            Model.manager mgr = Session[DTKeys.SESSION_ADMIN_INFO] as Model.manager;
            string busnieseNum = mgr.busnieseNum.ToString();
            string appNum = Session[DTKeys.SESSION_APP_INFO].ToString();
            string templatesNum = Session[DTKeys.SESSION_TEMPLATES_INFO].ToString();

            List<long> idList = new List<long>();
            foreach (RepeaterItem item in rptList.Items)
            {
                Model.bs_good_type_field field = new Model.bs_good_type_field();

                int fieldId = Convert.ToInt32(((HiddenField)item.FindControl("hidId")).Value);
                CheckBox cb = (CheckBox)item.FindControl("chkId");
                if (cb.Checked)
                {
                    idList.Add(fieldId);
                }
                field.id = fieldId;
                field.busnieseNum = busnieseNum;
                field.appNum = appNum;
                field.templatesNum = templatesNum;
                field.fieldCode = ((TextBox)item.FindControl("txtFieldCode")).Text;
                field.fieldName = ((TextBox)item.FindControl("txtFildName")).Text;
                field.fieldType = ((TextBox)item.FindControl("txtFieldType")).Text;
                var fieldLengthText = ((TextBox)item.FindControl("txtFieldLength")).Text;
                if (!String.IsNullOrWhiteSpace(fieldLengthText))
                    field.fieldLength = Convert.ToInt32(fieldLengthText);
                var fieldPrecisionText = ((TextBox)item.FindControl("txtFieldPrecision")).Text;
                if (!String.IsNullOrWhiteSpace(fieldPrecisionText))
                    field.fieldPrecision = Convert.ToInt32(fieldPrecisionText);
                field.fieldRemark = ((TextBox)item.FindControl("txtFieldRemark")).Text;
                field.goodTypeId = this.id;
                list.Add(field);
            }
            //移除指定的行
            list.RemoveAll(m => idList.Contains(m.id));

            this.rptList.DataSource = list;
            this.rptList.DataBind();
        }
        #endregion
    }
}